package net.dodoman.notepad;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.Vector;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;

//数据库对话框行为
class Database extends JDialog implements KeyListener, WindowListener {
	/**
	 * 
	 */
	private static final long serialVersionUID = 5514993094990448535L;
	JLabel lServer, lDbName, lSql, lUsername, lPassword;
	JTextField tServer, tDbName, tSql, tUsername;
	JPasswordField password;
	JButton bConection, bCancel;
	String strServer, strDbName, strSql, strUsername, strPassword;
	JPanel inputPane, buttonPane;

	public Database(JFrame databaseDialog) {
		super(databaseDialog, "连接数据库", true);
		Container contentPane = getContentPane();
		buttonPane = new JPanel();
		inputPane = new JPanel();
		contentPane.add(inputPane, BorderLayout.CENTER);
		inputPane.setLayout(new GridLayout(6, 2));
		// contentPane.setLayout();
		lServer = new JLabel("数据库服务器");
		lDbName = new JLabel("数据库名字");
		lSql = new JLabel("SQL语句");
		lUsername = new JLabel("数据库的用户名");
		lPassword = new JLabel("数据库的密码");
		tServer = new JTextField();
		tDbName = new JTextField();
		tSql = new JTextField("SELECT * FROM ");
		tUsername = new JTextField();
		password = new JPasswordField();
		bConection = new JButton("连接", new ImageIcon("ico/rs.gif"));
		bCancel = new JButton("取消", new ImageIcon("ico/rq.gif"));
		// 设置取消按钮事件响应
		bCancel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				setVisible(false);
			}
		});
		this.addWindowListener(this);
		inputPane.add(lServer);
		inputPane.add(tServer);
		inputPane.add(lDbName);
		inputPane.add(tDbName);
		inputPane.add(lSql);
		inputPane.add(tSql);
		inputPane.add(lUsername);
		inputPane.add(tUsername);
		inputPane.add(lPassword);
		inputPane.add(password);
		contentPane.add(buttonPane, BorderLayout.SOUTH);
		buttonPane.add(bConection);
		buttonPane.add(bCancel);
		setSize(390, 180);
		setResizable(false);
		// 设置确定按钮事件响应
		bConection.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				DatabaseQuery dbq = new DatabaseQuery(Database.this);
				dbq.getDatabaseInfo();
				dbq.setVisible(true);
			}
		});
		// 增加文本域事件响应
		tServer.addKeyListener(this);
		tDbName.addKeyListener(this);
		tSql.addKeyListener(this);
		tUsername.addKeyListener(this);
		password.addKeyListener(this);
	}

	// 数据库实现
	class DatabaseQuery extends JDialog {
		JScrollPane scroll;
		JPanel shutDownPanel = new JPanel();
		JButton bShut;
		Statement stat;
		ResultSet rs;
		final JDialog dbDialog;
		Connection conn;

		public DatabaseQuery(JDialog dbDialog) {
			super(dbDialog, "查询结果", true);
			this.dbDialog = dbDialog;
			setTitle("查询结果");
			setDefaultCloseOperation(HIDE_ON_CLOSE);
			setSize(300, 250);
		}

		//
		public void getDatabaseInfo() {
			// 获取文本域输入的信息
			strServer = tServer.getText().trim();
			strDbName = tDbName.getText().trim();
			strSql = tSql.getText().trim();
			strUsername = tUsername.getText().trim();
			strPassword = password.getText().trim();
			getContentPane().add(shutDownPanel, BorderLayout.SOUTH);
			bShut = new JButton("关闭", new ImageIcon("ico/exit.gif"));
			shutDownPanel.add(bShut);
			bShut.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					setVisible(false);
				}
			});
			Vector cloumn = new Vector();
			Vector rows = new Vector();
			try {

				// System.out.println(strSql);
				Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
				String url = "jdbc:microsoft:sqlserver://" + strServer
						+ ":1433;databaseName=" + strDbName + ";";
				String username = strUsername;
				String password = strPassword;
				conn = DriverManager.getConnection(url, username, password);
				// conn = getConnection();
				stat = conn.createStatement();
				rs = stat.executeQuery(strSql);
				ResultSetMetaData meta = rs.getMetaData();
				for (int i = 1; i <= meta.getColumnCount(); i++)
					cloumn.addElement(meta.getColumnName(i));
				while (rs.next()) {
					rows.addElement(getRowNext(rs, meta));
				}
				JTable table = new JTable(rows, cloumn);
				scroll = new JScrollPane(table);
				getContentPane().add(scroll, BorderLayout.CENTER);
			} catch (Exception e) {
				JOptionPane.showMessageDialog(DatabaseQuery.this, "数据库连接错误",
						"错误", JOptionPane.ERROR_MESSAGE);
				e.printStackTrace();
			}
		}

		public Vector getRowNext(ResultSet rs, ResultSetMetaData meta)
				throws Exception {
			Vector currentRow = new Vector();
			for (int i = 1; i <= meta.getColumnCount(); i++) {
				currentRow.addElement(rs.getString(i));
			}
			return currentRow;
		}
		// 从当前目录中获取"database.properties"的文件
		/*
		 * public Connection getConnection() throws Exception { Properties props =
		 * new Properties(); FileInputStream in = new
		 * FileInputStream("database.properties"); props.load(in); in.close();
		 * String drivers = props.getProperty("jdbc.drivers"); if (drivers !=
		 * null) System.setProperty("jdbc.drivers", drivers); String url =
		 * props.getProperty("jdbc.url") + strServer + ":1433;databaseName=" +
		 * strDbName + ";"; //System.out.println(url); String username =
		 * props.getProperty("jdbc.username") + strUsername; String password =
		 * props.getProperty("jdbc.password") + strPassword; return
		 * DriverManager.getConnection(url, username, password); }
		 */
	}

	public void keyTyped(KeyEvent e) {
	}

	public void keyPressed(KeyEvent e) {
	}

	public void keyReleased(KeyEvent e) {
		if (e.getSource() == password || e.getSource() == tUsername)
			bConection.setEnabled(true);
	}

	public void windowOpened(WindowEvent e) {
		bConection.setEnabled(false);
	}

	public void windowClosing(WindowEvent e) {
		// TODO 自动生成方法存根
	}

	public void windowClosed(WindowEvent e) {
		// TODO 自动生成方法存根
	}

	public void windowIconified(WindowEvent e) {
		// TODO 自动生成方法存根
	}

	public void windowDeiconified(WindowEvent e) {
		// TODO 自动生成方法存根
	}

	public void windowActivated(WindowEvent e) {
		// TODO 自动生成方法存根
	}

	public void windowDeactivated(WindowEvent e) {
		// TODO 自动生成方法存根
	}
}